package controllers

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"goconfcenter/core/consts"
	"goconfcenter/core/enums"
	"goconfcenter/core/response"
	"goconfcenter/dao/redis"
	"goconfcenter/pkg/Util"
	"goconfcenter/pkg/jwt"
	"goconfcenter/service"
	"goconfcenter/service/dto/bus"
	"goconfcenter/settings"
)

type LoginController struct {
}
//RandomImg 获取图片验证码
func (c *LoginController) RandomImg(context *gin.Context) {
	var randomImgResp bus.RandomImgResp
	imgCodeDTO := service.SecurityServiceInstance().GenImgCode(400, 400, 4, 4)
	randomImgResp.Img = imgCodeDTO.Img
	randomImgResp.ImgUuid = imgCodeDTO.UuId
	response.Success(context, consts.CurdStatusOkMsg, randomImgResp)
}
//DoLogin 登录
func (c *LoginController) DoLogin(context *gin.Context) {
	u := new(bus.LoginDTO)
	if err := context.ShouldBindJSON(u); err != nil {
		zap.L().Error("登录参数异常", zap.Error(err))
		response.ErrorParam(context, "")
		return
	}
	// 验证验证码
	if u.ImgUuid==""||!service.SecurityServiceInstance().VerifyImgCode(u.ImgUuid,u.ValidCode){
		response.Fail(context,consts.CodeInvalid,consts.CodeInvalidMsg,"")
		return
	}
	user := service.BackendUserServiceInstance().GetByUserName(u)
	if user == nil {
		response.Fail(context,consts.BusinessFail,consts.BusinessFailMsg,"用户不存在")
		return
	}
	frontPwd, err := Util.RsaDecryptByBase64(u.UserPwd, settings.Conf.AppConfig.MyPrivateKey)
	if err != nil {
		response.Fail(context,consts.BusinessFail,consts.BusinessFailMsg,"密码解密失败，请联系管理员")
		return
	}
	pwd := Util.Md5Salt(string(frontPwd), user.UserPwdExt)
	if pwd != user.UserPwd {
		response.Fail(context,consts.BusinessFail,consts.BusinessFailMsg,"用户名或者密码错误")
		return
	}
	if user.IsLock==enums.Yes.Value(){
		response.Fail(context,consts.BusinessFail,consts.BusinessFailMsg,"用户已锁定")
		return
	}
	token, _ := jwt.GenToken(user.ID)
	redis.Set(redis.GetRedisKey(redis.BackUserToken), token,redis.EXPIRED_DAY)
	// 清除历史的登录信息
	service.BackendUserServiceInstance().ClearBackendLoginUserInfo(user.ID)
	response.Success(context, consts.CurdStatusOkMsg, token)
	return
}
//GetUserInfo 获取用户基本信息
func (c *LoginController) GetUserInfo(context *gin.Context) {
	userId, exists := context.Get("userId")
	if exists {
		loginUser := service.BackendUserServiceInstance().GetInfo(userId.(int64))
		response.Success(context, consts.CurdStatusOkMsg, loginUser)
	} else {
		response.Fail(context,consts.BusinessFail,consts.BusinessFailMsg,"用户不存在")
	}
	return
}

func (c *LoginController) UserEnter(context *gin.Context) {
	response.Success(context, consts.CurdStatusOkMsg, true)
	return
}
// DoLogout 退出
func (c *LoginController) DoLogout(context * gin.Context)  {
	response.Success(context, consts.CurdStatusOkMsg, true)
	return
}
